import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { pb } from 'src/pb';
import { dialogConfirm, dialogPrompt } from '../components/dialog';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.page.html',
  styleUrls: ['./users.page.scss'],
})
export class UsersPage implements OnInit {
  config: pb.IConfig = {};
  constructor(private http: HttpService, private alertCtrl: AlertController) {}

  async ngOnInit() {
    this.config = await this.http.get('/api/config');
  }

  async add(connID: number) {
    const name = await dialogPrompt(
      this.alertCtrl,
      { header: '增加用户', subHeader: '输入用户名称' },
      ''
    );

    if (name) {
      await this.http.put(`/api/conn/add/${connID}`, {
        user: name,
        readonly: true,
      });

      this.config = await this.http.get('/api/config');
    }
  }

  async del(name: string, connID: number) {
    if (
      await dialogConfirm(this.alertCtrl, {
        header: '删除',
        subHeader: `是否确定删除用户 [ ${name} ] ?`,
      })
    ) {
      await this.http.put(`/api/conn/del/${connID}`, {
        user: name,
      });

      this.config = await this.http.get('/api/config');
    }
  }
}
